package myVecmathImp;

import java.nio.FloatBuffer;

import org.lwjgl.BufferUtils;

import ogl.vecmath.Color;
import ogl.vecmath.Vector;

public class MyColor implements Color {

	private float r;
	private float g;
	private float b;

	public float getR() {
		return r;
	};

	public float getG() {
		return g;
	};

	public float getB() {
		return b;
	};

	public MyColor(float r, float g, float b) {
		this.r = r;
		this.g = g;
		this.b = b;
	}

	public MyColor(Vector v) {
		this.r = v.x();
		this.g = v.y();
		this.b = v.z();
	}

	@Override
	public boolean isBlack() {
		return (r == 0.0 && g == 0.0 && b == 0.0);
	}

	@Override
	public Color add(MyColor c) {
		return new MyColor(r + c.getR(), g + getG(), b + getB());
	}

	@Override
	public Color modulate(float s) {
		return new MyColor(r * s, g * s, b * s);
	}

	@Override
	public Color modulate(MyColor c) {
		return new MyColor(r * c.getR(), g * c.getG(), b * c.getB());
	}

	@Override
	public Color clip() {
		MyColor c = new MyColor(Math.min(getR(), 1), Math.min(g, 1), Math.min(
				b, 1));
		return new MyColor(Math.max(c.getR(), 0), Math.max(c.getG(), 0),
				Math.max(c.getB(), 0));
	}

	@Override
	public float[] asArray() {
		return new float[] { r, g, b };
	}

	@Override
	public FloatBuffer asBuffer() {
		FloatBuffer buf = BufferUtils.createFloatBuffer(size());
		buf.put(r);
		buf.put(g);
		buf.put(b);
		buf.rewind();
		return buf;
	}

	@Override
	public void fillBuffer(FloatBuffer buf) {
		buf.put(r);
		buf.put(g);
		buf.put(b);
	}

	@Override
	public int toAwtColor() {
		MyColor c = (MyColor) clip();
		return (toInt(1.0f) << 24) | (toInt(c.getR()) << 16)
				| (toInt(c.getG()) << 8) | toInt(c.getB());
	}

	private static int toInt(float f) {
		return Math.round(f * 255.0f);
	}

	@Override
	public int compareTo(Color o) {
		if (r != o.getR()) {
			return ((r < o.getR()) ? 1 : -1);
		}
		if (g != o.getG()) {
			return ((g < o.getG()) ? 1 : -1);
		}
		if (b != o.getB()) {
			return ((b < o.getB()) ? 1 : -1);
		}
		return 0;
	}

	@Override
	public int size() {
		return 3;
	}

}
